<template>
	<wd-toast />
	<wd-popup v-model="dialogVisible" custom-style="width:80%; height:40%" lock-scroll :close-on-click-modal="false">
		<wd-form ref="formRef" :model="formData" :rules="formRules">
			<wd-cell-group border>
				<wd-card type="rectangle">
					<template #title>
						<view class="" style="display: flex;">
							<span style="display: flex;align-items: center;margin-left: 10px;">减签</span>
						</view>
					</template>
					<view class="">
						<wd-select-picker label="减签任务" label-width="100px" prop="id" v-model="formData.id"
							:columns="childrenTaskList" placeholder="请选择减签任务" clearable filterable value-key="id"
							label-key="nickname"></wd-select-picker>
						<wd-input label="减签理由" label-width="100px" prop="reason" clearable v-model="formData.reason"
							placeholder="请输入减签理由" />
					</view>
					<template #footer>
						<view class="flex justify-evenly mx-4 my-2">
							<wd-button type="primary" @click="submitForm" block size="small">确 定</wd-button>
							<wd-button type="error" @click="dialogVisible = false" block size="small">取 消</wd-button>
						</view>
					</template>
				</wd-card>
			</wd-cell-group>
			<view class="footer">
			</view>
		</wd-form>
	</wd-popup>
</template>
<script lang="ts" setup>
	import { ref } from 'vue'
	import * as TaskApi from '@/api/bpm/task'
	import { isEmpty } from '@/utils/is'
	import { useMessage, useToast } from 'wot-design-uni'

	defineOptions({ name: 'TaskSignDeleteForm' })


	const toast = useToast()  // 消息弹窗 // 消息弹窗
	const dialogVisible = ref(false) // 弹窗的是否展示
	const formLoading = ref(false) // 表单的加载中
	const formData = ref({
		id: '',
		reason: ''
	})
	const formRules = ref({
		id: [{ required: true, message: '必须选择减签任务', trigger: 'change' }],
		reason: [{ required: true, message: '减签理由不能为空', trigger: 'blur' }]
	})

	const formRef = ref() // 表单 Ref
	const childrenTaskList = ref([])
	/** 打开弹窗 */
	const open = async (id : string) => {
		childrenTaskList.value = await TaskApi.getChildrenTaskList(id)
		if (isEmpty(childrenTaskList.value)) {
			toast.warning('当前没有可减签的任务')
			return false
		}
		dialogVisible.value = true
		resetForm()
	}
	defineExpose({ open }) // 提供 openModal 方法，用于打开弹窗

	/** 提交表单 */
	const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
	const submitForm = async () => {
		// 校验表单
		if (!formRef) return
		const valid = await formRef.value.validate()
		if (!valid) return
		// 提交请求
		formLoading.value = true
		try {
			await TaskApi.signDeleteTask(formData.value)
			toast.success('减签成功')
			dialogVisible.value = false
			// 发送操作成功的事件
			emit('success')
		} finally {
			formLoading.value = false
		}
	}

	/** 重置表单 */
	const resetForm = () => {
		formData.value = {
			id: '',
			reason: ''
		}
	}
</script>